<!--
    自定义的类似smart-select的选择组件，从提供的url里获取数据，选择，然后返回，带分页，带延迟搜索功能

    用法：
    <f7-custom-smart-select
      title="单选测试"
      id="id2"
      listStyle="margin: 0;"
      :defaultVal="xxx"
      idProp="EngineeringId"
      nameProp="EngineeringName"
      url="/Api/ApiEngineering/list"
      @done="done"
      :multiple="false"
      :searchDelay="2000"
    >
        <template v-slot:before>
            xxxxx
        </template>
        <template v-slot:after>
            xxxxx
        </template>
    </f7-custom-smart-select>

    done(retVal) {
        console.log(retVal);
    }

    备注：id，表示popup的id，唯一标识，如果一个页面只有一个该组件实例，可以不写，若有多个，就一定要指定不同的id
        title，显示的标题
        url，必选，获取数据的接口，返回的数据格式需要为
                    {
                        data: [],
                        startIndex: xx,
                        recordsTotal: xx
                    }
        idProp，必选，id字段，用于遍历上面的data数组
        nameProp，必须，name字段，用于遍历上面的data数组，并显示类似标题的内容
        @done，提供一个方法来接收选中后返回来的值

 -->
<template>
  <f7-list :style="listStyle" :inset="inset" inline-labels no-hairlines-md>
    <slot name="before"></slot>
    <f7-list-item @click="openPopup" :title="title" link="#">
      <span style slot="after">{{ after || defaultVal }}</span>
    </f7-list-item>
    <slot name="after"></slot>

    <f7-popup :id="id">
      <f7-page infinite :infinite-preloader="true" @infinite="dataQuery">
        <f7-navbar>
          <f7-nav-left>
            <f7-link icon-material="arrow_back" @click="closePopup"></f7-link>
          </f7-nav-left>
          <f7-nav-title>{{ title }}</f7-nav-title>
          <f7-nav-right></f7-nav-right>
        </f7-navbar>
        <f7-custom-searchbar
          :delay="searchDelay"
          :search-container="searchContainer"
          :search-in="searchIn"
          @search="searchQuery"
          v-model="searchValue"
        ></f7-custom-searchbar>

        <f7-list v-if="multiple" media-list class="margin-top search-list">
          <f7-list-item
            checkbox
            @change="checkboxChange($event.target.checked, item[idProp], item[nameProp])"
            name="f7-custom-smart-select-checkbox"
            v-for="item in query.data"
            :key="item[idProp]"
            :title="item[nameProp]"
          ></f7-list-item>
        </f7-list>

        <f7-list v-if="!multiple" media-list class="margin-top search-list">
          <f7-list-item
            radio
            name="f7-custom-smart-select-radio"
            @change="radioChange(item[idProp], item[nameProp])"
            v-for="item in query.data"
            :key="item[idProp]"
            :title="item[nameProp]"
          ></f7-list-item>
        </f7-list>
      </f7-page>
    </f7-popup>
  </f7-list>
</template>
<script>
import _ from "lodash";
export default {
  props: {
    title: {
      type: String,
      default: ""
    },
    value: {
      type: String,
      default: ""
    },
    inset: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: "f7-custom-smart-select-popup"
    },
    idProp: {
      type: String
    },
    nameProp: {
      type: String
    },
    url: {
      type: String
    },
    searchDelay: {
      type: Number,
      default: 2000
    },
    searchContainer: {
      type: String,
      default: ".search-list"
    },
    searchIn: {
      type: String,
      default: ".item-text"
    },
    defaultVal: {
      type: String
    },
    listStyle: {
      type: String
    },
    clickRefresh: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      query: {
        data: []
      },
      after: "",
      retVals: {},
      retVal: null,
      searchValue: "",
      start: 0,
      length: 20,
      recordsTotal: null,
      loadFlag: true
    };
  },
  methods: {
    checkboxChange(checked, itemId, itemName) {
      if (checked) {
        this.retVals[itemId] = itemName;
      } else {
        delete this.retVals[itemId];
      }
    },
    radioChange(itemId, itemName) {
      // 触发事件
      this.retVal = itemId;
      this.after = itemName;
      this.closePopup();
    },
    closePopup() {
      // 触发done事件，返回选中值
      let self = this;

      if (self.multiple) {
        let retArr = [];
        let after = "";
        for (let o in self.retVals) {
          let json = {};
          json[self.idProp] = o;
          json[self.nameProp] = self.retVals[o];
          after = after + json[self.nameProp] + ",";
          retArr.push(json);
        }
        self.after = after.substr(0, after.length - 1);
        self.$emit("done", retArr);
      } else {
        self.$emit("done", this.retVal);
      }

      let popup = self.$f7.popup.get("#" + this.id);
      if (popup) {
        popup.close();
      }
    },
    openPopup() {
      if (this.query.data.length == 0 || this.clickRefresh) {
        this.$emit("onBeforeQuery", "");
        this.searchQuery();
      }
      let popup = this.$f7.popup.get("#" + this.id);
      if (popup) {
        popup.open();
      }
    },
    searchQuery() {
      // 设置start为0，数组清空，然后才加载数据
      this.start = 0;
      this.query.data = [];
      this.loadData();
    },
    dataQuery() {
      if (this.loadFlag) {
        if (this.recordsTotal && this.query.data.length >= this.recordsTotal) {
          this.$f7.dialog.toast("已全部加载完毕");
        } else {
          this.loadFlag = false;
          this.loadData();
        }
      }
    },
    loadData(rqurl = this.url) {
      let self = this;

      if (rqurl) {
        let params = { start: self.start, length: self.length };
        if (self.searchValue) {
          params[`query[${self.nameProp}]`] = self.searchValue;
        }
        self.$f7.request.postJSON(
          rqurl,
          params,
          r => {
            if (r) {
              if (_.isArray(r.data)) {
                _.each(r.data, item => {
                  self.query.data.push(item);
                });
                // self.start = r.startIndex + self.length;
                self.start += self.length;
                self.recordsTotal = r.recordsTotal;
                self.$emit("onAfterQuery", r.data);
              }
            }
            self.loadFlag = true;
          },
          r => {
            self.loadFlag = true;
          }
        );
      }
    }
  }
};
</script>
<style scoped>
</style>
